<template>
  <div class="history-card">
    <el-card shadow="never" class="card-container">
      <!-- 卡片标题 -->
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Clock /></el-icon>
            <span class="header-title">操作历史</span>
          </div>
          <div class="header-right">
            <el-dropdown @command="handleMenuCommand">
              <el-button type="text" size="small">
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="refresh">
                    <el-icon><Refresh /></el-icon>
                    刷新记录
                  </el-dropdown-item>
                  <el-dropdown-item command="clear" divided>
                    <el-icon><Delete /></el-icon>
                    清空历史
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 操作历史列表 -->
      <div class="history-content">
        <!-- 无历史记录时显示 -->
        <div v-if="!operationHistory || operationHistory.length === 0" class="empty-history">
          <el-empty 
            description="暂无操作记录" 
            :image-size="60"
          >
            <div class="empty-actions">
              <el-button size="small" @click="generateSampleHistory">
                <el-icon><Plus /></el-icon>
                生成示例记录
              </el-button>
            </div>
          </el-empty>
        </div>

        <!-- 有历史记录时显示时间线 -->
        <div v-else class="history-timeline">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in displayHistory"
              :key="index"
              :timestamp="formatTime(record.time)"
              :type="getTimelineType(record.action)"
              :icon="getActionIcon(record.action)"
              :color="getTimelineColor(record.action)"
              placement="top"
              class="timeline-item"
            >
              <div class="timeline-content">
                <!-- 操作信息 -->
                <div class="operation-info">
                  <div class="operation-header">
                    <span class="operation-action">{{ record.action }}</span>
                    <el-tag 
                      :type="getActionTagType(record.action)" 
                      size="small"
                      class="action-tag"
                    >
                      {{ getActionCategory(record.action) }}
                    </el-tag>
                  </div>
                  
                  <div class="operation-details" v-if="record.details">
                    <p class="details-text">{{ record.details }}</p>
                  </div>
                  
                  <div class="operation-meta">
                    <div class="meta-left">
                      <el-icon><User /></el-icon>
                      <span class="operator">{{ record.operator }}</span>
                    </div>
                    
                    <div class="meta-right" v-if="record.changes">
                      <el-tooltip :content="record.changes" placement="top">
                        <el-icon class="changes-icon"><Edit /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                </div>

                <!-- 变更详情（可展开） -->
                <div v-if="record.changes && record.showDetails" class="change-details">
                  <el-divider content-position="left">变更详情</el-divider>
                  <div class="changes-list">
                    <div v-for="change in parseChanges(record.changes)" :key="change.field" class="change-item">
                      <span class="change-field">{{ change.field }}：</span>
                      <span class="change-from">{{ change.from || '空' }}</span>
                      <el-icon class="change-arrow"><Right /></el-icon>
                      <span class="change-to">{{ change.to || '空' }}</span>
                    </div>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="operation-actions" v-if="record.canRevert || record.changes">
                  <el-button-group>
                    <el-button 
                      v-if="record.changes"
                      size="small" 
                      text 
                      @click="toggleDetails(index)"
                    >
                      <el-icon><View /></el-icon>
                      {{ record.showDetails ? '收起详情' : '查看详情' }}
                    </el-button>
                    
                    <el-button 
                      v-if="record.canRevert"
                      size="small" 
                      text 
                      type="warning"
                      @click="revertOperation(record, index)"
                    >
                      <el-icon><RefreshLeft /></el-icon>
                      撤销操作
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 显示更多/收起按钮 -->
        <div v-if="operationHistory && operationHistory.length > displayLimit" class="history-actions">
          <el-button 
            text 
            @click="toggleShowAll"
            class="show-more-btn"
          >
            <el-icon>
              <component :is="showAll ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
            {{ showAll ? '收起历史记录' : `显示全部 ${operationHistory.length} 条记录` }}
          </el-button>
        </div>
      </div>

      <!-- 统计信息 -->
      <div v-if="operationHistory && operationHistory.length > 0" class="history-stats">
        <el-divider content-position="left">统计信息</el-divider>
        <div class="stats-grid">
          <div class="stat-item">
            <el-icon class="stat-icon"><DataAnalysis /></el-icon>
            <div class="stat-info">
              <span class="stat-value">{{ operationHistory.length }}</span>
              <span class="stat-label">总操作数</span>
            </div>
          </div>
          
          <div class="stat-item">
            <el-icon class="stat-icon" color="#34C759"><CircleCheck /></el-icon>
            <div class="stat-info">
              <span class="stat-value">{{ getActionCount('创建') + getActionCount('保存') }}</span>
              <span class="stat-label">保存次数</span>
            </div>
          </div>
          
          <div class="stat-item">
            <el-icon class="stat-icon" color="#FF9500"><Edit /></el-icon>
            <div class="stat-info">
              <span class="stat-value">{{ getActionCount('编辑') + getActionCount('修改') }}</span>
              <span class="stat-label">编辑次数</span>
            </div>
          </div>
          
          <div class="stat-item">
            <el-icon class="stat-icon" color="#007AFF"><Timer /></el-icon>
            <div class="stat-info">
              <span class="stat-value">{{ getLastOperationTime() }}</span>
              <span class="stat-label">最后操作</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { 
  Clock, More, Refresh, Delete, Plus, User, Edit, View, RefreshLeft,
  Right, DataAnalysis, CircleCheck, Timer, ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  operationHistory: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['refresh-history', 'clear-history', 'revert-operation'])

// 显示控制
const showAll = ref(false)
const displayLimit = 5

// 显示的历史记录
const displayHistory = computed(() => {
  if (!props.operationHistory) return []
  
  if (showAll.value) {
    return props.operationHistory
  }
  
  return props.operationHistory.slice(0, displayLimit)
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  
  const now = new Date()
  const operationTime = new Date(time)
  const diffMs = now.getTime() - operationTime.getTime()
  const diffMinutes = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)
  
  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return operationTime.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 获取时间线类型
const getTimelineType = (action) => {
  if (action.includes('创建') || action.includes('新建')) return 'success'
  if (action.includes('删除') || action.includes('移除')) return 'danger'
  if (action.includes('编辑') || action.includes('修改')) return 'warning'
  return 'primary'
}

// 获取时间线颜色
const getTimelineColor = (action) => {
  if (action.includes('创建') || action.includes('新建')) return '#34C759'
  if (action.includes('删除') || action.includes('移除')) return '#FF3B30'
  if (action.includes('编辑') || action.includes('修改')) return '#FF9500'
  return '#007AFF'
}

// 获取操作图标
const getActionIcon = (action) => {
  if (action.includes('创建') || action.includes('新建')) return 'Plus'
  if (action.includes('删除') || action.includes('移除')) return 'Delete'
  if (action.includes('编辑') || action.includes('修改')) return 'Edit'
  if (action.includes('保存')) return 'Check'
  return 'Operation'
}

// 获取操作标签类型
const getActionTagType = (action) => {
  if (action.includes('创建') || action.includes('新建')) return 'success'
  if (action.includes('删除') || action.includes('移除')) return 'danger'
  if (action.includes('编辑') || action.includes('修改')) return 'warning'
  return 'primary'
}

// 获取操作分类
const getActionCategory = (action) => {
  if (action.includes('创建') || action.includes('新建')) return '创建'
  if (action.includes('删除') || action.includes('移除')) return '删除'
  if (action.includes('编辑') || action.includes('修改')) return '编辑'
  if (action.includes('保存')) return '保存'
  if (action.includes('查看')) return '查看'
  return '其他'
}

// 解析变更详情
const parseChanges = (changes) => {
  if (!changes) return []
  
  // 简单解析格式："字段名: 旧值 → 新值"
  try {
    return changes.split(';').map(change => {
      const parts = change.split(':')
      if (parts.length !== 2) return null
      
      const field = parts[0].trim()
      const values = parts[1].split('→')
      
      return {
        field,
        from: values[0]?.trim(),
        to: values[1]?.trim()
      }
    }).filter(Boolean)
  } catch (error) {
    return [{ field: '变更详情', from: '', to: changes }]
  }
}

// 切换详情显示
const toggleDetails = (index) => {
  const record = displayHistory.value[index]
  record.showDetails = !record.showDetails
}

// 切换显示全部
const toggleShowAll = () => {
  showAll.value = !showAll.value
}

// 获取操作次数
const getActionCount = (actionType) => {
  if (!props.operationHistory) return 0
  return props.operationHistory.filter(record => 
    record.action.includes(actionType)
  ).length
}

// 获取最后操作时间
const getLastOperationTime = () => {
  if (!props.operationHistory || props.operationHistory.length === 0) return '无'
  const lastRecord = props.operationHistory[0] // 假设按时间倒序排列
  return formatTime(lastRecord.time)
}

// 菜单命令处理
const handleMenuCommand = async (command) => {
  switch (command) {
    case 'refresh':
      emit('refresh-history')
      ElMessage.success('历史记录已刷新')
      break
      
    case 'clear':
      try {
        await ElMessageBox.confirm(
          '确定要清空所有操作历史记录吗？此操作不可撤销。',
          '确认清空',
          {
            confirmButtonText: '确定清空',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        emit('clear-history')
        ElMessage.success('历史记录已清空')
      } catch {
        // 用户取消操作
      }
      break
  }
}

// 撤销操作
const revertOperation = async (record, index) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤销操作"${record.action}"吗？`,
      '确认撤销',
      {
        confirmButtonText: '确定撤销',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('revert-operation', { record, index })
    ElMessage.success('操作已撤销')
  } catch {
    // 用户取消操作
  }
}

// 生成示例历史记录
const generateSampleHistory = () => {
  const sampleHistory = [
    {
      time: new Date().toISOString(),
      action: '创建客户档案',
      operator: '当前用户',
      details: '创建了新的客户档案记录',
      canRevert: false
    },
    {
      time: new Date(Date.now() - 5 * 60000).toISOString(),
      action: '保存基础信息',
      operator: '当前用户',
      details: '保存了客户基础信息',
      changes: '客户姓名: 空 → 张三;客户性别: 空 → 男',
      canRevert: true,
      showDetails: false
    }
  ]
  
  // 这里应该通过emit传递给父组件
  ElMessage.success('已生成示例历史记录')
}
</script>

<style lang="scss" scoped>
.history-card {
  .card-container {
    border: 1px solid #E5E5EA;
    border-radius: 12px;
    overflow: hidden;
    
    :deep(.el-card__header) {
      padding: 16px 20px;
      background: #F2F2F7;
      border-bottom: 1px solid #E5E5EA;
    }
    
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .header-icon {
          font-size: 18px;
          color: #8E8E93;
        }
        
        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #3C3C43;
        }
      }
    }
  }
  
  // 空状态样式
  .empty-history {
    text-align: center;
    padding: 20px;
    
    .empty-actions {
      margin-top: 16px;
    }
  }
  
  // 时间线样式
  .history-timeline {
    :deep(.el-timeline) {
      padding-left: 0;
      
      .el-timeline-item {
        padding-bottom: 20px;
        
        &:last-child {
          padding-bottom: 0;
        }
        
        .el-timeline-item__timestamp {
          font-size: 12px;
          color: #8E8E93;
          margin-bottom: 4px;
        }
      }
    }
    
    .timeline-content {
      background: #FAFAFA;
      border: 1px solid #E5E5EA;
      border-radius: 8px;
      padding: 16px;
      margin-left: 20px;
      
      .operation-info {
        .operation-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          .operation-action {
            font-size: 14px;
            font-weight: 600;
            color: #3C3C43;
          }
          
          .action-tag {
            font-size: 10px;
          }
        }
        
        .operation-details {
          margin-bottom: 12px;
          
          .details-text {
            font-size: 12px;
            color: #8E8E93;
            margin: 0;
            line-height: 1.4;
          }
        }
        
        .operation-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: #8E8E93;
          
          .meta-left {
            display: flex;
            align-items: center;
            gap: 4px;
            
            .el-icon {
              font-size: 12px;
            }
          }
          
          .meta-right {
            .changes-icon {
              font-size: 14px;
              color: #007AFF;
              cursor: help;
            }
          }
        }
      }
      
      .change-details {
        margin-top: 12px;
        
        .changes-list {
          .change-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            font-size: 12px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .change-field {
              color: #3C3C43;
              font-weight: 500;
            }
            
            .change-from {
              color: #FF3B30;
              text-decoration: line-through;
            }
            
            .change-arrow {
              color: #8E8E93;
              font-size: 10px;
            }
            
            .change-to {
              color: #34C759;
              font-weight: 500;
            }
          }
        }
      }
      
      .operation-actions {
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #E5E5EA;
      }
    }
  }
  
  // 显示更多按钮样式
  .history-actions {
    text-align: center;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #E5E5EA;
    
    .show-more-btn {
      font-size: 12px;
    }
  }
  
  // 统计信息样式
  .history-stats {
    margin-top: 16px;
    
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
      
      .stat-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px;
        background: #FAFAFA;
        border-radius: 6px;
        
        .stat-icon {
          font-size: 16px;
          color: #007AFF;
        }
        
        .stat-info {
          flex: 1;
          
          .stat-value {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #3C3C43;
          }
          
          .stat-label {
            font-size: 10px;
            color: #8E8E93;
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .history-card {
    .card-container {
      :deep(.el-card__body) {
        padding: 16px;
      }
    }
    
    .timeline-content {
      padding: 12px;
      margin-left: 16px;
    }
    
    .stats-grid {
      grid-template-columns: 1fr;
    }
    
    .operation-actions {
      .el-button-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
        
        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>